import pymysql
import traceback

class MysqlUtil():
    def __init__(self):
        self.host = 'localhost',
        self.user = 'root',
        self.password = 'andy123456',
        self.db = 'student_system',
        self.charset = 'utf8'
        self.connect()

    def connect(self):
        self.connection = pymysql.connect(
            host='localhost',
            user='root',
            password='andy123456',
            db='student_system',
            charset='utf8',
            cursorclass= pymysql.cursors.DictCursor
        )

    def execute(self,sql):
        """
        执行增/删/修改
        :param sql: sql语句
        :return: 影响的记录条数
        """
        try:
            with self.connection.cursor() as cursor:
                result = cursor.execute(sql)
            self.connection.commit()
            return result
        except:
            self.traceback()
            # 回滚操作
            self.connection.rollback()

    def find(self,sql,fetch_one=False):
        """
        查找一条记录或全部记录
        :param sql: sql语句
        :param fetch_one: bool值，如果为True,查找一条，如果为False,查找多条
        :return: 查找的记录
        """
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql)
                if fetch_one:
                    result = cursor.fetchone()
                else:
                    result = cursor.fetchall()
                return result
        except:
            self.traceback()

    def traceback(self):
        with open('log.txt', 'a') as file:
            traceback.print_exc(file=file)
            file.flush()

    def close(self):
        if getattr(self,"connection",0):
            self.connection.close()

    def __del__(self):
        self.close()

if __name__ == "__main__":
    db = MysqlUtil()
    sql = 'select version()'
    result = db.find(sql,fetch_one=True)
    print(result)